/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package packageBusiness;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import packageModel.*;
import packageException.*;
import packageDataAccess.*;
import java.util.StringTokenizer;
/**
 *
 * @author laurent
 */
public class BricoWebUserBusiness 
{
     private BricoWebData bricoWebData = new BricoWebData();
     
     public BricoWebUser GetBricowebUser(String userId) throws ConnectionException
    {
        return bricoWebData.getBricowebUser(userId);
    }
     
    public void setBricowebUser(BricoWebUser user, String rePassword) throws ConnectionException, RegisterException
    {
        boolean error = false;
        boolean registerError[] = new boolean[8];
        for(int i = 0; i<8 ; i++) { registerError[i] = false;}
        
        if(testUserID(user.getUserID())) { registerError[0] = true; error = true;}                                                 
        if(testString(user.getFirstName())) { registerError[1] = true; error = true;}
        if(testString(user.getLastName())) { registerError[2] = true; error = true;}
        if(testString(user.getDeliveryAddress())) { registerError[3] = true; error = true;}
        if(testEmail(user.getEmail())) { registerError[4] = true; error = true;}
        if(testPhoneNumber(user.getPhoneNumber())) { registerError[5] = true; error = true;}
        if(testPassword(user.getPassword())) { registerError[6] = true; error = true;}
        if(!user.getPassword().equals(rePassword)) { registerError[7] = true; error = true;}

        if(error == true)
            throw new RegisterException(registerError);
        else
            bricoWebData.setBricowebUser(user);
    }
    public void setBasket(Basket basket) throws ConnectionException
    {
        bricoWebData.setBasket(basket);
        // vérifier champs
    }
    
    public ArrayList<Category> getAllCategories() throws ConnectionException
    {
        return bricoWebData.getAllCategories();
    }
    
    public ArrayList<Product> getProductOfCategory(int categoryId) throws ConnectionException
    {
        return bricoWebData.getProductOfCategory(categoryId);
    }
         
    public void login(String usr, String pw) throws  ConnectionException, LoginException
    {
        bricoWebData.login(usr, pw);
    }
     
    public Product getProduct(int productId) throws ConnectionException
    {
        return bricoWebData.getProduct(productId);
    }
    
    public double calculatePromo(Product product)
    {
        return (1 - product.getPromotion().getDiscountPercentage()/100)*product.getUnitaryPrice();  
    }
    
    public double calculatePriceTot(Product product, int quantityProd)
    {
        GregorianCalendar dateNow = new GregorianCalendar();
        
        if(product.getPromotion() != null && product.getPromotion().getStartDate().getTimeInMillis() < dateNow.getTimeInMillis() && product.getPromotion().getEndDate().getTimeInMillis() > dateNow.getTimeInMillis())
            if(product.getPromotion().getDiscountPercentage()!= null)
                return calculatePromo(product)*quantityProd;
            else if(quantityProd >= product.getPromotion().getQuantityToPurchase())
                return (quantityProd -(quantityProd / product.getPromotion().getQuantityToPurchase())*product.getPromotion().getQuantityOffered())*product.getUnitaryPrice();
            else
                return quantityProd*product.getUnitaryPrice();
        else
            return quantityProd*product.getUnitaryPrice();
    }
    
    public double calculatePriceUnit(Product product)
    {
        GregorianCalendar dateNow = new GregorianCalendar();
        
        if(product.getPromotion() != null && product.getPromotion().getStartDate().getTimeInMillis() < dateNow.getTimeInMillis() && product.getPromotion().getEndDate().getTimeInMillis() > dateNow.getTimeInMillis())
            if(product.getPromotion().getDiscountPercentage()!= null)
                return product.getUnitaryPrice()*(1-product.getPromotion().getDiscountPercentage()/100);
            else
                return product.getUnitaryPrice();
        else
            return product.getUnitaryPrice();
    }
    
    public double calculatePriceTotOrder(Basket basket)
    {
        double priceTot = 0;
        
        for (ProductsLine prodLine : basket.getHashProductsLine().values( ) )
        {
            priceTot += calculatePriceTot(prodLine.getProduct(),prodLine.getNbProducts());
        }
        
        return priceTot;
    }
     
    public boolean testString(String stringtoTest)
    {
        if(removeSpaces(stringtoTest).isEmpty())
            return true;
        return false;
    }
    
    public boolean testUserID(String userIDtoTest)
    {
        BricoWebUser  user = null;
        
        try
        {
            user = bricoWebData.getBricowebUser(userIDtoTest);
        }
        catch(Exception e)
        {
            if(userIDtoTest.isEmpty())
                return true;
            return false;
        }
        if(user != null || userIDtoTest.length() < 6)
            return true;
         return false;
    }
    
    public boolean testEmail(String emailtoTest)
    {
         if(emailtoTest.isEmpty() || !emailtoTest.matches("^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)+$"))
             return true;
         return false;
    }
    
    public boolean testPassword(String passwordToTest)
    {
        if(passwordToTest.length() < 6)
             return true;
         return false;
    }
    
    public boolean testPhoneNumber(String phoneNumberToTest)
    {
        if(phoneNumberToTest.isEmpty() || !phoneNumberToTest.matches("(\\+[0-9][0-9][0-9]( [0-9][0-9])+)|([0-9]+)"))
             return true;
         return false;
    }
    
    public String removeSpaces(String s) 
    {
          StringTokenizer st = new StringTokenizer(s," ",false); // false fait que le caractère " " est le délimiteur
          String t="";
          while (st.hasMoreElements()) t += st.nextElement();
          return t;
    }
}
